import { createRouter, createWebHistory } from 'vue-router'
import {getToken} from "@/utils/auth";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from "@/store";
import {ElMessage} from "element-plus";
import Layout from '@/layout/AppMain.vue'

NProgress.configure({ showSpinner: false })

export const constantRoutes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: 'index',
        name: 'Index',
        meta: { title: '首页',icon:'home',cache: true, affix: true },
        component: () => import('@/views/index.vue')
      },
    ]
  },

]

export const  whiteRoutes = [
  {
    path: '/auth',
    name: 'login',
    hidden: true,
    component: () => import('@/views/Login')
  },
  {
    path: '/register',
    name: 'register',
    hidden: true,
    component: () => import('@/views/Register')
  },
  {
    path: '/404',
    name: 'NotFound',
    hidden: true,
    component: () => import('@/views/error/404')
  },
  {
    path: '/401',
    hidden: true,
    component: () => import('@/views/error/401')
  },
]

export const commonRoutes = [
  {
    path: '/common',
    hidden: true,
    component: () => import('@/views/system/common/index'),
    children: [
      {
        path: 'overview',
        name: 'overview',
        meta: { title: '概览', icon: 'dashboard', affix: true },
        component: () => import('@/components/common/OverviewInfo')
      },
      {
        path: 'config',
        name: 'config',
        meta: { title: '配置', icon: 'system', affix: true },
        component: () => import('@/components/common/ConfigInfo')
      }
      ,
      {
        path: 'log',
        name: 'log',
        meta: { title: '日志', icon: 'form', affix: true },
        component: () => import('@/components/common/LogInfo')
      }
      ,
      {
        path: 'user',
        name: 'user',
        meta: { title: '我的', icon: 'user', affix: true },
        component: () => import('@/components/common/UserInfo')
      }
    ]
  },
]

/**
 * 白名单路由，可直接访问
 * @type {string[]}
 */
const whiteList = ['/auth', '/register']

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: [...commonRoutes,...whiteRoutes]
})

/**
 * 路由前置守卫
 */
router.beforeEach((to, from,next) => {
  NProgress.start();

  const hasToken = getToken();

  if (hasToken) {
    // 如果已经有 Token，处理登录后的跳转逻辑
    if (to.path === '/auth') {
      next({ path: '/' });
      NProgress.done();
    } else {
      // 如果 roles 为空，需要获取角色信息获取角色信息，判断是否需要动态添加路由
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then((res) => {
          const roles = res.roles;
          if (roles.length>0 && roles.includes('common')){
            store.dispatch('GameInfo').then(() => {});
            if (to.path.startsWith("/common")){
              next()
            }else {

              next('/common/overview')
            }
          }else {
            // 获取路由表并动态添加
            store.dispatch('GenerateRoutes').then((accessRoutes) => {
              accessRoutes.forEach(route => {
                router.addRoute(route);
              });
              next('/');
            });
          }
        }).catch((err) => {
          store.dispatch('LogOut').then(() => {
            ElMessage.error(err || '验证失败，请重新登录');
            next({ path: '/auth' });
          }).finally(() => {
            NProgress.done();
          });
        });
      } else {
        next();
        NProgress.done();
      }
    }
  } else {
    // 没有 Token 的情况下，跳转到登录页面
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next('/auth');
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done()
})
export default router
